// miniprogram/pages/freeLearn1/freeLearn1.js
var httpUtils = require('../../utils/httpUtils')
var api = require("../../utils/API")
var utils = require("../../utils/utils")
var commonFields = require("../../utils/commonFields")
var innerAudioContext = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        IMAGE_URL: httpUtils.IMAGE_URL,
        choosedSubject: 1, //所选择的科目
        questionList: [],
        totalCount: 0,
        correctCount: 0, //回答正确题目数
        errorCount: 0, //回答错误题目数
        answerList: [], //答案列表
        currentQuestion: null,
        currentQuestionIndex: 1,
        IsAnswerSheetOpen: false,
        IsExplanOpen: false,
        currentAnswer: {
            subIndex: 0,
            cusAnswer: '',
            IsAnswered: false,
            IsCorrect: true
        },
        optionAType: "md-radio-button-off",
        optionBType: "md-radio-button-off",
        optionCType: "md-radio-button-off",
        optionDType: "md-radio-button-off",
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            choosedSubject: options.subject
        });
        this.getQuestionsPagedList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    getQuestionsPagedList() {
        var _this = this;
        httpUtils.postRequest(api.API_FREE_QUESTION_LIST, {
            subject: _this.data.choosedSubject
        },
            res => {
                _this.initQuestions(res.data)
            },
            fail => {
                console.log(fail)
            }
        );
    },
    initQuestions(data) {
        var answerList = []
        for (let j = 0; j < data.length; j++) {
            answerList.push({
                subIndex: j,
                cusAnswer: '',
                IsAnswered: false,
                IsCorrect: true
            });
        }
        this.setData({
            questionList: data,
            totalCount: data.length,
            answerList: answerList,
            currentAnswer: answerList[this.data.currentQuestionIndex - 1]
        })
        var currentQuestion = data[this.data.currentQuestionIndex - 1];
        if (currentQuestion.IsKey == 1 && !currentQuestion.IsKeyAdded) { //如果是关键字题目
            let keyword = currentQuestion.KeyText;
            currentQuestion.Question = currentQuestion.Question.replace(
                keyword,
                `<span class="blink">${keyword}</span>`
            );
            currentQuestion.Option1 = currentQuestion.Option1.replace(
                keyword,
                `<span class="blink">${keyword}</span>`
            );
            currentQuestion.Option2 = currentQuestion.Option2.replace(
                keyword,
                `<span class="blink">${keyword}</span>`
            );
            currentQuestion.Option3 = currentQuestion.Option3.replace(
                keyword,
                `<span class="blink">${keyword}</span>`
            );
            currentQuestion.Option4 = currentQuestion.Option4.replace(
                keyword,
                `<span class="blink">${keyword}</span>`
            );
            currentQuestion.IsKeyAdded = true;

        }
        this.setData({
            currentQuestion: currentQuestion
        });
        //定位到记忆的题目位置
        var subjectIndex = utils.getStorageSync(this.data.choosedSubject == 1 ? commonFields.free1 : commonFields.free4);
        if (!subjectIndex) {
            subjectIndex = 1
        }

        var e = {
            currentTarget: {
                dataset: {
                    index: subjectIndex
                }
            }
        }
        this.turnTo(e)
    },
    //选择按钮
    tapAnswer: function (e) {
        var option = e.currentTarget.dataset.index;
        // 没有回答
        if (!this.data.currentAnswer.IsAnswered) {
            if (this.data.currentQuestion.QuesTypeText !== '多选') {
                var cusAnswer = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].cusAnswer';
                var IsCorrect = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsCorrect';
                var IsAnswered = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsAnswered';
                var IsCorrectValue = this.data.currentQuestion.Answer === option;
                this.setData({
                    [cusAnswer]: option,
                    [IsCorrect]: IsCorrectValue,
                    [IsAnswered]: true
                })
                this.setData({
                    currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
                });

                this.setData({
                    optionAType: this.answerOptionClass('A'),
                    optionBType: this.answerOptionClass('B'),
                    optionCType: this.answerOptionClass('C'),
                    optionDType: this.answerOptionClass('D'),
                });

                //回答以后的统计
                if (IsCorrectValue) { //回答正确到下一题
                    this.setData({
                        correctCount: this.data.correctCount + 1,
                    });

                    let _this = this;
                    setTimeout(function () {
                        console.log('定时器')
                        _this.nextQuestion();
                    }, 500)
                } else {
                    this.playAudio();
                    this.setData({
                        errorCount: this.data.errorCount + 1,
                    })
                }
                //计算选择

            } else {
                if (!this.data.currentAnswer.cusAnswer.includes(option)) {
                    var cusAnswer = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].cusAnswer';
                    var cusAnswerValue = this.data.currentAnswer.cusAnswer + option + ","
                    this.setData({
                        [cusAnswer]: cusAnswerValue
                    });
                    this.setData({
                        currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
                    });
                    if (option == "A") {
                        this.setData({
                            optionAType: this.answerOptionClass('A')
                        });
                    } else if (option == "B") {
                        this.setData({
                            optionBType: this.answerOptionClass('B')
                        });
                    } else if (option == "C") {
                        this.setData({
                            optionCType: this.answerOptionClass('C')
                        });
                    } else if (option == "D") {
                        this.setData({
                            optionDType: this.answerOptionClass('D')
                        });
                    }
                }
            }

        }
    },
    //提交多选的答案
    submitAnswers() {
        if (this.data.currentQuestion.QuesTypeText === "多选") {
            let cusAnswer = this.data.currentAnswer.cusAnswer
                .substring(0, this.data.currentAnswer.cusAnswer.length - 1)
                .split(",");
            let subjectAnswer = this.data.currentQuestion.Answer.split(",");
            var IsCorrectValue = cusAnswer.sort().toString() === subjectAnswer.sort().toString();
            var IsCorrect = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsCorrect';
            var IsAnswered = 'answerList[' + (this.data.currentQuestionIndex - 1) + '].IsAnswered';
            this.setData({
                [IsCorrect]: IsCorrectValue,
                [IsAnswered]: true
            });
            //回答以后的统计
            if (IsCorrectValue) { //回答正确到下一题
                this.setData({
                    correctCount: this.data.correctCount + 1,
                });

                let _this = this;
                setTimeout(function () {
                    console.log('定时器')
                    _this.nextQuestion();
                }, 500)
            } else {
                this.playAudio();
                this.setData({
                    errorCount: this.data.errorCount + 1,
                })
            }
            this.setData({
                optionAType: this.answerOptionClass('A'),
                optionBType: this.answerOptionClass('B'),
                optionCType: this.answerOptionClass('C'),
                optionDType: this.answerOptionClass('D'),
            });
        }
    },
    answerOptionClass: function (option) {
        let className = 'md-radio-button-off';
        if (this.data.currentQuestion.QuesTypeText === '多选') {
            if (this.data.currentAnswer.IsAnswered) { //已经提交答案
                if (this.data.currentQuestion.Answer.includes(option) && this.data.currentAnswer.cusAnswer.includes(option)) { //答案里有这个选项 且 选择了这个选项
                    className = 'md-checkmark-circle'
                } else if (this.data.currentQuestion.Answer.includes(option) && !this.data.currentAnswer.cusAnswer.includes(option)) { //答案里有  但  没选
                    className = 'md-checkmark-circle-outline'
                } else if (!this.data.currentQuestion.Answer.includes(option) && this.data.currentAnswer.cusAnswer.includes(option)) { //答案里没有 但 选了
                    className = 'md-close-circle'
                }
            } else { //没有提交答案的如果选过
                if (this.data.currentAnswer.cusAnswer.includes(option)) {
                    className = 'md-checkmark-circle'
                }
            }
        } else {
            if (this.data.currentAnswer.IsAnswered) {
                if (this.data.currentQuestion.Answer.includes(option)) {
                    className = 'md-checkmark-circle'
                } else if (!this.data.currentQuestion.Answer.includes(option) && this.data.currentAnswer.cusAnswer.includes(option)) {
                    className = 'md-close-circle'
                }
            }
        }
        return className

    },
    preQuestion() {
        if (innerAudioContext) {
            innerAudioContext.destroy();
        }
        if (this.data.currentQuestionIndex > 1) {
            this.setData({
                currentQuestionIndex: this.data.currentQuestionIndex - 1,
            })
            this.setData({
                currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
            })
            var currentQuestion = this.data.questionList[this.data.currentQuestionIndex - 1];
            if (currentQuestion.IsKey == 1 && !currentQuestion.IsKeyAdded) { //如果是关键字题目
                let keyword = currentQuestion.KeyText;
                currentQuestion.Question = currentQuestion.Question.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option1 = currentQuestion.Option1.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option2 = currentQuestion.Option2.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option3 = currentQuestion.Option3.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option4 = currentQuestion.Option4.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.IsKeyAdded = true;

            }
            this.setData({
                currentQuestion: currentQuestion
            });
            this.setData({
                optionAType: this.answerOptionClass('A'),
                optionBType: this.answerOptionClass('B'),
                optionCType: this.answerOptionClass('C'),
                optionDType: this.answerOptionClass('D'),
            });
            utils.setStorageSync(this.data.choosedSubject == 1 ? commonFields.free1 : commonFields.free4, this.data.currentQuestionIndex);
        }
    },
    nextQuestion() {
        if (innerAudioContext) {
            innerAudioContext.destroy();
        }
        if (this.data.currentQuestionIndex !== this.data.totalCount) {
            this.setData({
                currentQuestionIndex: this.data.currentQuestionIndex + 1,
            })
            this.setData({
                currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
            })
            var currentQuestion = this.data.questionList[this.data.currentQuestionIndex - 1];
            if (currentQuestion.IsKey == 1 && !currentQuestion.IsKeyAdded) { //如果是关键字题目
                let keyword = currentQuestion.KeyText;
                currentQuestion.Question = currentQuestion.Question.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option1 = currentQuestion.Option1.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option2 = currentQuestion.Option2.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option3 = currentQuestion.Option3.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option4 = currentQuestion.Option4.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.IsKeyAdded = true;

            }
            this.setData({
                currentQuestion: currentQuestion
            });
            this.setData({
                optionAType: this.answerOptionClass('A'),
                optionBType: this.answerOptionClass('B'),
                optionCType: this.answerOptionClass('C'),
                optionDType: this.answerOptionClass('D'),
            });
            utils.setStorageSync(this.data.choosedSubject == 1 ? commonFields.free1 : commonFields.free4, this.data.currentQuestionIndex);

        }
    },
    turnTo(e) {
        if (innerAudioContext) {
            innerAudioContext.destroy();
        }
        var index = e.currentTarget.dataset.index;
        if (index !== this.data.currentQuestionIndex) {
            this.setData({
                currentQuestionIndex: index,
            })
            this.setData({
                currentAnswer: this.data.answerList[this.data.currentQuestionIndex - 1]
            })
            var currentQuestion = this.data.questionList[this.data.currentQuestionIndex - 1];
            if (currentQuestion.IsKey == 1 && !currentQuestion.IsKeyAdded) { //如果是关键字题目
                let keyword = currentQuestion.KeyText;
                currentQuestion.Question = currentQuestion.Question.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option1 = currentQuestion.Option1.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option2 = currentQuestion.Option2.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option3 = currentQuestion.Option3.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.Option4 = currentQuestion.Option4.replace(
                    keyword,
                    `<span class="blink">${keyword}</span>`
                );
                currentQuestion.IsKeyAdded = true;

            }
            this.setData({
                currentQuestion: currentQuestion
            });
            this.setData({
                optionAType: this.answerOptionClass('A'),
                optionBType: this.answerOptionClass('B'),
                optionCType: this.answerOptionClass('C'),
                optionDType: this.answerOptionClass('D'),
            });
            utils.setStorageSync(this.data.choosedSubject == 1 ? commonFields.free1 : commonFields.free4, this.data.currentQuestionIndex);

        }
    },
    //打开答题板
    showAnswerSheet() {
        this.setData({
            IsAnswerSheetOpen: true
        });
    },
    onCloseAnswerSheet() {
        this.setData({
            IsAnswerSheetOpen: false
        });
    },
    //打开讲解
    showExplan() {
        this.setData({
            IsExplanOpen: true
        });
    },
    onCloseExplan() {
        this.setData({
            IsExplanOpen: false
        });
    },
    //播放音频
    playAudio() {
        if (this.data.currentQuestion.ExpAudio) {
            if (innerAudioContext) {
                innerAudioContext.destroy();
            }
            innerAudioContext = wx.createInnerAudioContext();
            innerAudioContext.autoplay = true
            innerAudioContext.src = this.data.IMAGE_URL + this.data.currentQuestion.ExpAudio;
            console.log(this.data.IMAGE_URL + this.data.currentQuestion.ExpAudio)

            innerAudioContext.onPlay(() => {
                console.log('开始播放')
            })
            innerAudioContext.onError((res) => {
                console.log(res.errMsg)
                console.log(res.errCode)
            })
        }
    }
})